<template>
  <div class="chat-container">
    <div class="chat-header">
      <el-button type="text" icon="el-icon-back" @click="goBack">返回</el-button>
      <h2>
        {{ sellerInfo.realName }}
      </h2>
    </div>
    <div class="chat-content">
      <div class="message" v-for="(item, index) in messages" :key="index">
        <div class="message-seller" v-if="item.sender != userInfo.userId">
          <RouterLink :to="`/seller/${item.sender}`">
            <div class="avatar">
              <el-avatar :src="sellerInfo.avatarUrl" size="small"></el-avatar>
            </div>
          </RouterLink>
          <div class="bubble">
            <div class="time">{{ formatTimeDate(item.timestamp) }}</div>
            <div class="text">{{ item.content }}</div>
          </div>
        </div>
        <div class="message-buyer" v-else>
          <div class="bubble">
            <div class="time">{{ formatTimeDate(item.timestamp) }}</div>
            <div class="text">{{ item.content }}</div>
          </div>
          <div class="avatar">
            <el-avatar :src="userInfo.avatarUrl" size="small"></el-avatar>
          </div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <el-input
        v-model="newMessage"
        type="textarea"
        :rows="2"
        placeholder="请输入消息"
        @keyup.enter.native="sendMessage"
      ></el-input>
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from "vue";
import { onBeforeRouteLeave, onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useChatStore } from "@/stores/chat";
import { ElMessage } from "element-plus";
import { userInfoStore } from "@/stores/user";
import { formatTimeDate } from "@/utils/common";
import { getUserInfoAPI } from "@/apis/user";

const chatStore = useChatStore();
const route = useRoute();
const router = useRouter();
const userInfo = userInfoStore().userInfo;
// 当前参与者的 ID
const participantId = ref(route.params.id);
const newMessage = ref("");

// 获取当前会话的消息
const fetchMessages = async () => {
  await chatStore.fetchMessages({ offset: 0, size: 100 });
};

// 创建会话
const createConversation = async () => {
  if (participantId.value) {
    await chatStore.createConversation(participantId.value);
    await fetchMessages();
  }
};

// 发送消息
const sendMessage = async () => {
  if (newMessage.value.trim() === "") return;
  chatStore.setNewMessage(newMessage.value);
  chatStore.sendMessage(participantId.value);
  newMessage.value = ""; // 清空输入框
};

// 返回上一页
const goBack = () => {
  router.back();
};
const sellerInfo = ref({});
const getSellerInfo = async () => {
  const res = await getUserInfoAPI({ userId: participantId.value });
  sellerInfo.value = res.data;
};

// 在组件挂载时初始化 WebSocket 连接
onMounted(async () => {
  console.log("route.form: ", route);
  // if (route.form === "/detail") {
  await getSellerInfo();
  await createConversation();
  // }
  await chatStore.initWebSocket();
});

const messages = ref([]);

// 监听消息列表的变化并更新
watch(
  () => chatStore.messages,
  (newMessages) => {
    messages.value = newMessages;
    console.log("messages.value: ", messages.value);
  },
  { deep: true }
);

// 在组件卸载时关闭 WebSocket 连接
onUnmounted(() => {
  chatStore.closeWebSocket();
});
</script>

<style scoped lang="scss">
.chat-container {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  margin-left: 10px;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.message {
  margin-bottom: 15px;
}

.message-seller {
  display: flex;
  align-items: flex-start;
}

.message-buyer {
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
}

.avatar {
  margin-right: 10px;
}

.message-buyer .avatar {
  margin-left: 10px;
  margin-right: 0;
}

.bubble {
  max-width: 70%;
  padding: 10px;
  border-radius: 4px;
  position: relative;
}

.message-seller .bubble {
  background-color: #fff;
}

.message-buyer .bubble {
  background-color: #1e90ff;
  color: white;
}

.time {
  font-size: 12px;
  color: #ccc;
  margin-bottom: 5px;
}

.text {
  word-wrap: break-word;
}

.chat-input {
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
}

:deep(.el-textarea) {
  width: calc(100% - 80px);
}

:deep(.el-button) {
  margin-left: 10px;
}
</style>
